package co.gov.medellin.sdep.sisdep.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import co.gov.medellin.sdep.sisdep.model.Citacion;

public class CitacionDAOImpl extends JdbcDaoSupport implements ICitacionDAO {

    private InsertOperation insertOperation;

    private UpdateOperation updateOperation;

    private DeleteOperation deleteOperation;

    private DeleteByPrimaryKey deleteByPrimaryKey;

    private FindByPrimaryKeyQuery findByPrimaryKeyQuery;

    private FindByCriteriaQuery findByCriteriaQuery;

    private FindAllQuery findAllQuery;
    
    private FindByDocumentoQuery findByDocumentoQuery;
    
    private VerificarDocumentoQuery verificarDocumentoQuery;

    private FindByActiveStateQuery findByActiveStateQuery;

	private static final String SELECT = "SELECT * FROM OPE_CITACION_T ";
	private static final String WHERE = " WHERE ";
	private static final String PARAMETER = " ?, ";

    public void delete(Citacion citacion) {
		deleteOperation.execute( citacion  );
	}

	public void deleteByPrimaryKey(long id) {
		deleteByPrimaryKey.execute(id);
	}

	public Citacion findByPrimaryKey(long login) {
		return findByPrimaryKeyQuery.runQuery(login);
	}

	public void insert(Citacion citacion) {
		insertOperation.execute( citacion );
	}

	public void update(Citacion citacion) {
		updateOperation.execute( citacion );
	}

	public Citacion findByCriteria(Citacion  citacion) {
		return findByCriteriaQuery.runQuery(citacion);
	}

	public List load() {
		return findAllQuery.runQuery();
	}
	
	public List loadByDocumento(Citacion citacion) {
		return findByDocumentoQuery.runQuery(citacion);
	}

	public String verificarDocumento(Citacion  citacion) {
		return verificarDocumentoQuery.runQuery(citacion);
	}
	
	public Citacion findByActiveState(Citacion  citacion) {
		return findByActiveStateQuery.runQuery(citacion);
	}

	public void initDao() {
    	insertOperation   = new InsertOperation( getDataSource() );
    	updateOperation = new UpdateOperation(  getDataSource() );
    	//deleteOperation = new DeleteOperation(  getDataSource() );
    	//deleteByPrimaryKey = new DeleteByPrimaryKey( getDataSource());
    	//findByPrimaryKeyQuery   = new FindByPrimaryKeyQuery(  getDataSource() );
    	//findByCriteriaQuery = new FindByCriteriaQuery(  getDataSource() );
    	findAllQuery = new FindAllQuery( getDataSource() );
    	findByDocumentoQuery = new FindByDocumentoQuery( getDataSource() );
    	verificarDocumentoQuery = new VerificarDocumentoQuery( getDataSource() );
    	//findByActiveStateQuery = new FindByActiveStateQuery( getDataSource() );
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO OPE_CITACION_T ("
				  + " ID, "
				  + " ID_CITACION_LUGAR, "
				  + " CODIGO, "
				  + " FECHA, "
				  + " HORA, "
				  + " ID_TIPO_DOCUMENTO, "
				  + " DOCUMENTO_PERSONA, "
				  + " ASISTE, "
				  + " PAGO_MULTA, "
				  + " REINCIDENTE, "
				  + " VALOR_MULTA, "
				  + " OBSERVACION, "
				  + " ESTADO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA "				  
				  + ") VALUES ("
			  	  + " OPE_CITACION_SEC.nextVal, "
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.DATE));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			compile();
		}
		public void execute(Citacion citacion) {
			InsertOperation.this.update( new Object[]{				
				citacion.getIdCitacionLugar(),
				citacion.getCodigo(),
				citacion.getFecha(),
				citacion.getHora(),
				citacion.getIdTipoDocumento(),
				citacion.getDocumentoPersona(),
				citacion.getAsiste(),
				citacion.getPagoMulta(),
				citacion.getReincidente(),
				citacion.getValorMulta(),
				citacion.getObservacion(),
				citacion.getEstado(),
				citacion.getUsuarioCrea()			
				});
		}
    }

    // ------------- UpdateOperation -------------------------------------
    class UpdateOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE OPE_CITACION_T SET "					  
					  + " ID_CITACION_LUGAR = ? ,"
					  + " CODIGO = ? ,"
					  + " FECHA = ? ,"
					  + " HORA = ? ,"
					  + " ID_TIPO_DOCUMENTO = ? ,"
					  + " DOCUMENTO_PERSONA = ? ,"
					  + " ASISTE = ? ,"
					  + " PAGO_MULTA = ? ,"
					  + " REINCIDENTE = ? ,"
					  + " VALOR_MULTA = ? ,"
					  + " OBSERVACION = ? ,"
					  + " ESTADO = ? ,"					  
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE"
				  	  + WHERE
				  	  + " ID = ? ";	
		public  UpdateOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.DATE));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));			
			compile();
		}
		public void execute(Citacion citacion) {
			UpdateOperation.this.update( new Object[]{				
				citacion.getIdCitacionLugar(),
				citacion.getCodigo(),
				citacion.getFecha(),
				citacion.getHora(),
				citacion.getIdTipoDocumento(),
				citacion.getDocumentoPersona(),
				citacion.getAsiste(),
				citacion.getPagoMulta(),
				citacion.getReincidente(),
				citacion.getValorMulta(),
				citacion.getObservacion(),
				citacion.getEstado(),				
				citacion.getUsuarioModifica(),				
				citacion.getId(),
				});
		}
    }

    // ------------- DeleteOperation -------------------------------------
    class DeleteOperation extends SqlUpdate	{
		private static final String sql = "DELETE FROM OPE_CITACION_T "
										+ WHERE
			  	  	  					+ " CODIGO = ? ";
		public DeleteOperation(DataSource ds) {
			super(ds,sql);
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
		}
		public void execute(Citacion citacion) {
			this.update( new Object[]{
				citacion.getCodigo(),
			});
		}
	}

    // ------------- DeleteByPrimaryKey ----------------------------------
    class DeleteByPrimaryKey extends SqlUpdate	{
		private static final String sql = "DELETE FROM OPE_CITACION_T "
										+ WHERE + " 1=1";
		public DeleteByPrimaryKey(DataSource ds) {
			super(ds,sql);
			compile();
		}	
		public void execute(long id) {
			this.update( new Object[]{
			});
		}	
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperation extends MappingSqlQuery {
		public BaseQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			Citacion citacion = new Citacion();
				citacion.setId(new Long(rs.getLong("ID")));
				citacion.setIdCitacionLugar(new Long(rs.getLong("ID_CITACION_LUGAR")));
				citacion.setIdCitacionLugarStr(rs.getString("ID_CITACION_LUGAR"));
				citacion.setCodigo(rs.getString("CODIGO"));
				citacion.setFecha(rs.getDate("FECHA"));		
				citacion.setHora(rs.getString("HORA"));
				citacion.setIdTipoDocumento(new Long(rs.getLong("ID_TIPO_DOCUMENTO")));
				citacion.setIdTipoDocumentoStr(rs.getString("ID_TIPO_DOCUMENTO"));
				citacion.setDocumentoPersona(rs.getString("DOCUMENTO_PERSONA"));
				citacion.setAsiste(rs.getString("ASISTE"));
				citacion.setPagoMulta(rs.getString("PAGO_MULTA"));
				citacion.setReincidente(rs.getString("REINCIDENTE"));
				citacion.setValorMulta(new Long(rs.getLong("VALOR_MULTA")));
				citacion.setValorMultaStr(rs.getString("VALOR_MULTA"));
				citacion.setObservacion(rs.getString("OBSERVACION"));
				citacion.setEstado(rs.getString("ESTADO"));
				citacion.setUsuarioCrea(rs.getString("USUARIO_CREA"));
				citacion.setFechaCrea(rs.getDate("FECHA_CREA"));		
				citacion.setUsuarioModifica(rs.getString("USUARIO_MODIFICA"));
				citacion.setFechaModifica(rs.getDate("FECHA_MODIFICA"));	
				
				if(citacion.getAsiste().equals("S"))
					citacion.setAsisteChk(true);
				if(citacion.getReincidente().equals("S"))
					citacion.setReincidenteChk(true);
				if(citacion.getPagoMulta().equals("S"))
					citacion.setPagoMultaChk(true);
			return citacion;
		}
    }
	
	 // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class ValidarDocumentoOperation extends MappingSqlQuery {
		public ValidarDocumentoOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			
				String existe = rs.getString("EXISTE");
			return existe;
		}
    }

    // ------------- FindByPrimaryKeyQuery -------------------------------
    class FindByPrimaryKeyQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1";
    	public FindByPrimaryKeyQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Citacion runQuery(long id) {
			List result =  execute( new Object[]{new Long(id)});
			if ( result.size() > 0 ) {
        		return (Citacion) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    class FindByCriteriaQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
			//For required criteria elements uncomment required values
			  	  	  					//+ " AND ID = ? "
			  	  	  					//+ " AND ID_CITACION_LUGAR = ? "
			  	  	  					//+ " AND CODIGO = ? "
			  	  	  					//+ " AND FECHA = ? "
			  	  	  					//+ " AND HORA = ? "
			  	  	  					//+ " AND NOMBRE_PERSONA = ? "
			  	  	  					//+ " AND DOCUMENTO_PERSONA = ? "
			  	  	  					//+ " AND ASISTE = ? "
			  	  	  					//+ " AND PAGO_MULTA = ? "
			  	  	  					//+ " AND REINCIDENTE = ? "
			  	  	  					//+ " AND VALOR_MULTA = ? "
			  	  	  					//+ " AND OBSERVACION = ? "
			  	  	  					//+ " AND ESTADO = ? "
			  	  	  					//+ " AND USUARIO_CREA = ? "
			  	  	  					//+ " AND FECHA_CREA = ? "
			  	  	  					//+ " AND USUARIO_MODIFICA = ? "
			  	  	  					//+ " AND FECHA_MODIFICA = ? "
										//+ "";
    	public FindByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
    		//For required criteria elements uncomment required values
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			compile();
    	}
    	public Citacion runQuery(Citacion citacion) {
			List result =  execute( new Object[]{
			//For required criteria elements uncomment required values
				//citacion.getId(),
				//citacion.getIdCitacionLugar(),
				//citacion.getCodigo(),
				//citacion.getFecha(),
				//citacion.getHora(),
				//citacion.getNombrePersona(),
				//citacion.getDocumentoPersona(),
				//citacion.getAsiste(),
				//citacion.getPagoMulta(),
				//citacion.getReincidente(),
				//citacion.getValorMulta(),
				//citacion.getObservacion(),
				//citacion.getEstado(),
				//citacion.getUsuarioCrea(),
				//citacion.getFechaCrea(),
				//citacion.getUsuarioModifica(),
				//citacion.getFechaModifica(),
				});
			if ( result.size() > 0 ) {
        		return (Citacion) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindAllQuery ----------------------------------------    
    class FindAllQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
    	public FindAllQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public List runQuery() {
			List result =  execute();
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByDocumentoQuery ----------------------------------------    
    class FindByDocumentoQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " ID_TIPO_DOCUMENTO=? AND (DOCUMENTO_PERSONA =? OR '%' = ?)";
    	public FindByDocumentoQuery(DataSource ds) {
    		super(ds,sql);
			declareParameter( new SqlParameter(Types.INTEGER) );
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
    	}
    	public List runQuery(Citacion citacion) {
			List result =  execute( new Object[]{
					citacion.getIdTipoDocumento(),
					citacion.getDocumentoPersona(),
					citacion.getDocumentoPersona()
			});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }
    
    // ------------- FindByDocumentoQuery ----------------------------------------    
    class VerificarDocumentoQuery extends ValidarDocumentoOperation {
		private static final String sql = "SELECT COALESCE(COUNT(*),0) AS EXISTE  " +
											" FROM ADM_PERSONA_T WHERE IDENTIFICACION =? AND "
										 	+ " ID_TIPO_IDENTIFICACION=? ";
										 
    	public VerificarDocumentoQuery(DataSource ds) {
    		super(ds,sql);			
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.INTEGER) );
			compile();
    	}
    	public String runQuery(Citacion citacion) {
			List result =  execute( new Object[]{							
					citacion.getDocumentoPersona(),
					citacion.getIdTipoDocumento()
			});
			if ( result.size() > 0 ) {
        		return  result.get(0).toString();
        	} else {
        		return null;
        	}
    	}
    }    
    
    // ------------- FindByActiveStateQuery  -----------------------------
    class FindByActiveStateQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1";
    	public FindByActiveStateQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Citacion runQuery(Citacion citacion) {
			List result =  execute( new Object[]{
			});
			if ( result.size() > 0 ) {
        		return (Citacion) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

}
